package org.example.yunshu.demos.service;

import lombok.extern.slf4j.Slf4j;
import org.example.yunshu.demos.constant.Constants;
import org.example.yunshu.demos.constant.HttpSessionNullException;
import org.example.yunshu.demos.mapper.UserMapper;
import org.example.yunshu.demos.model.Enter;
import org.example.yunshu.demos.model.UserInfo;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;

@Slf4j
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public Object login(UserInfo userInfo, String inputCaptcha, HttpSession session) {
        Enter enter = new Enter() ;

        String captcha = (String) session.getAttribute(Constants.ADMIN_KAPTCHA_SESSION_KEY);
        if(captcha.equalsIgnoreCase(inputCaptcha)){
            enter.setCaptcha(true);
        }else {
            log.info("captcha验证码错误");
            enter.setBool(false);
            return enter ;
        }
        if(!StringUtils.hasLength(userInfo.getUserName()) || !StringUtils.hasLength(userInfo.getPassword())){
            enter.setBool(false);
            log.info("用户或密码为null");
            return enter ;
        }
        // 在数据库里查询用户密码是否正确 ;
         UserInfo check = userMapper.getUserByName(userInfo.getUserName()) ;
         if(check != null && check.getPassword().equals(userInfo.getPassword())) {
             enter.setBool(true);
             check.setPassword("");
             session.setAttribute(Constants.USERINFO_KEY , check);
         }
             return enter ;
    }

    public Object insertUserInfo(UserInfo userInfo, String inputCaptcha, HttpSession session) {
        Enter enter = new Enter() ;

        String captcha = (String) session.getAttribute(Constants.ADMIN_KAPTCHA_SESSION_KEY);
        if(captcha.equalsIgnoreCase(inputCaptcha)){
            enter.setCaptcha(true);
        }else {
            log.info("captcha验证码错误");
            enter.setBool(false);
            return enter ;
        }
         if(userMapper.getUserByName(userInfo.getUserName()) != null){
           enter.setBool(false);
           return enter ;
         }
         int check =  userMapper.insertUserInfo(userInfo);
         if(check > 0){
             enter.setBool(true);
         }
         return enter ;
    }

    public Object getUserInfo(HttpSession httpSession) {
         UserInfo userInfo = (UserInfo) httpSession.getAttribute(Constants.USERINFO_KEY);

         UserInfo result = new UserInfo() ;
        result.setUserId(userInfo.getUserId());
        result.setUserName(userInfo.getUserName());
        result.setHeadImage(userInfo.getHeadImage());
        return result ;
    }
}
